import {
	baseUrl,
	baseImgUrl
} from '../baseUrl.js';
import store from '../store.js';
import md5 from '../md5.js';
const http = (url, data, method = 'POST') => {
	method = method.toUpperCase();
	const header = {
		'Content-Type': 'application/json',
	};
	if (method == 'POST' || method == 'PUT' || method == 'PATCH') {
		// header['Content-Type'] = 'application/x-www-form-urlencoded';
		data = JSON.stringify(data)
	}
	var userInfo = store.get('user_info')
	var getParams = {
		appid: 1,
		_timestamp: `${new Date().getTime()}`,
		openid: userInfo ? userInfo.openid : '',
		volunteer_id: userInfo ? userInfo.volunteer_id : '',
	};
	header['sign'] = sign(getParams);

	return new Promise((resolve, reject) => {
		uni.request({
			url: baseUrl + url + build_query(getParams),
			method: method,
			data,
			header: header,
			success: res => {
				if (res.data.errno == 0) {
					resolve(res.data.data);
				} else {
					uni.showToast({
						title: res.data.errmsg || "未知错误",
						icon: 'none',
					})
					reject(res);
				}
			},
			fail: err => {
				console.log(err);
				uni.showToast({
					title: "请求错误",
					icon: 'none',
				})
				reject(err);
			},
		});
	})
}

const uploadImage = (string) => {
	const that = this;
	return new Promise((resolve, reject) => {
		uni.chooseImage({
			success: (chooseImageRes) => {
				const tempFilePaths = chooseImageRes.tempFilePaths;
				uni.uploadFile({
					url: `${baseUrl}/auction/upload/imageUpload`,
					filePath: tempFilePaths[0],
					name: 'file',
					formData: {},
					success: (uploadFileRes) => {
						if (uploadFileRes.statusCode == 200) {
							let imgUrl = baseImgUrl + JSON.parse(uploadFileRes.data);
							if (string) {
								console.log(getCurP());
								getCurP().$data[string] = imgUrl;
							}
							console.log(imgUrl);
							resolve(imgUrl);
						} else {
							reject(uploadFileRes);
						}

					},
					fail: (err) => {
						reject(err);
					}
				});
			}
		});
	})
}

const getCurP = () => {
	let pages = getCurrentPages();
	return pages[pages.length - 1];
}

const sign = (data) => {

	var newkey = Object.keys(data).sort();
	var str = '';
	//先用Object内置类的keys方法获取要排序对象的属性名，再利用Array原型上的sort方法对获取的属性名进行排序，newkey是一个数组

	for (var i = 0; i < newkey.length; i++) { //遍历newkey数组
		if (newkey[i] !== 'sign') {
			str += newkey[i] + data[newkey[i]];
		}
	}
	str += "jako000dd12kaYYKK";

	return md5(str);
}

const build_query = (data) => {
	var str = "?";
	for (var i in data) {
		str += i + "=" + data[i] + "&"
	}

	return str.substring(0, str.length - 1)
}

export {
	http,
	uploadImage
};
